import goodsList from './data'

// 深拷贝 避免影响原数据
let list = [...goodsList];

// 计算总数量
let getTotalNum = () => {
    let num = 0;
    list.forEach(item => {
        num += item.count
    })
    return `${num.toFixed(2)}件`
}
// 计算总金额
let getTotalPrice = () => {
    let num = 0;
    list.forEach(item => {
        num += item.count * item.price
    })
    return `${num.toFixed(2)}元`
}

let renderPage = () => {
    let str = ''
    list.forEach(item => {
        str += `
        <tr>
            <td>${item.name}</td>
            <td>${item.price}</td>
            <td>${item.count}</td>
            <td>${item.price * item.count}</td>
        </tr>
        `
    })
    str += `
        <tr>
            <td colspan=2>总计</td>
            <td>${getTotalNum()}</td>
            <td>${getTotalPrice()}</td>
        </tr>
    `
    document.querySelector('#tbody').innerHTML = str;
}
// renderPage()

class Cart {
    constructor(arr=list) { // 默认参数
        // arr是购物车中的数据
        this.list = arr;
    }
    // 计算总数量
    getTotalNum = () => {
        let num = 0;
        this.list.forEach(item => {
            num += item.count
        })
        return `${num}件`
    }
    // 计算总金额
    getTotalPrice = () => {
        let num = 0;
        this.list.forEach(item => {
            num += item.count * item.price
        })
        return `${num}元`
    }
    // 渲染页面
    renderPage = () => {
        let str = ''
        this.list.forEach(item => {
            str += `
            <tr>
                <td>${item.name}</td>
                <td>${item.price}</td>
                <td>${item.count}</td>
                <td>${item.price * item.count}</td>
            </tr>
            `
        })
        str += `
            <tr>
                <td colspan=2>总计</td>
                <td>${getTotalNum()}</td>
                <td>${getTotalPrice()}</td>
            </tr>
        `
        document.querySelector('#tbody').innerHTML = str;
    }
}

// 实例化，生成一个购物车示例
let cart1 = new Cart();
cart1.renderPage()